from rest_framework import serializers

from goods.models import SKUImage, SKU


class SKUSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')


class SKUImageSerializer(serializers.ModelSerializer):
    sku = serializers.StringRelatedField(label='sku商品名称')
    sku_id = serializers.IntegerField(label='sku商品id')

    class Meta:
        model = SKUImage
        exclude = ('create_time', 'update_time')

    @staticmethod
    def validate_sku_id(value):
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('SKU商品不存在')
        return value

    def create(self, validated_data):
        sku_image = SKUImage.objects.create(**validated_data)
        sku = sku_image.sku
        if not sku.default_image:
            sku.default_image = sku_image
            sku.save()
        return sku_image
